package com.woniu.woniu_bx.controller;

import cn.hutool.json.JSONObject;
import com.woniu.woniu_bx.exception.CaptchaException;
import com.woniu.woniu_bx.exception.PasswordExistException;
import com.woniu.woniu_bx.exception.UserExistsException;
import com.woniu.woniu_bx.pojo.ResponseEntity;
import com.woniu.woniu_bx.pojo.User;
import com.woniu.woniu_bx.service.UserService;
import com.woniu.woniu_bx.vo.UserLoginVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author : 王泰元
 * @className: UserLoginController
 * @description: TODO
 * @date : 2022/9/7 11:02
 */
@RestController
@Slf4j
public class UserLoginController {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private UserService userService;

    // 未登录，返回 401
    @RequestMapping("/login/unAuthority")
    public ResponseEntity unAuthority() {
        return ResponseEntity.INVALID_TOKEN("未登录", null);
    }


    // 通过密码登录
    @PostMapping("/login/byPwd")
    public ResponseEntity loginByPwd(@RequestBody User user) {
        log.debug("账号密码登录，user: {}", user);

        User byAccount = userService.getByAccount(user.getAccount());

        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

        //要回传的json对象，携带用户的id以、是否是陪玩，这两个信息
        JSONObject jsonObject = new JSONObject();

        if (byAccount == null) {
            throw new UserExistsException("账号不存在");
        } else if (!passwordEncoder.matches(user.getPassword(), byAccount.getPassword())) {
            throw new PasswordExistException("密码不正确");
        } else if ("n".equals(byAccount.getStatus())) {
            throw new UserExistsException("该用户已被锁定");
        } else {
            //(1)返回用户的id
            //(2)如果是陪玩的话，继续返回其陪玩的认证
            jsonObject.set("userId", byAccount.getId());

            if(byAccount.getAuthPw().equalsIgnoreCase("y")){
                jsonObject.set("authPW", "y");
            }
        }

        return ResponseEntity.SUCCESS("登录成功", jsonObject.toString());
    }


    /**
     * 通过手机号验证码登录
     *
     * @param userLoginVo 包含手机号和验证码的 view object
     * @return 响应
     */
    @PostMapping("/login/byCaptcha")
    public ResponseEntity loginByCaptcha(@RequestBody UserLoginVo userLoginVo) {
        log.debug("手机验证码登录，userLoginVo: {}", userLoginVo);

        User user = userService.getByPhone(userLoginVo.getTelephone());
        if (user == null) {
            throw new UserExistsException("手机号未注册");
        } else if ("n".equals(user.getStatus())) {
            throw new UserExistsException("该用户已被锁定");
        }

        // 从缓存中获取验证码
        String captcha = (String) redisTemplate.opsForValue().get(userLoginVo.getTelephone() + "_captcha");

        if (StringUtils.hasLength(captcha) && captcha.equals(userLoginVo.getCaptcha())) {
            return ResponseEntity.SUCCESS("登录成功", user.getId());
        } else {
            throw new CaptchaException("验证码错误或已过期");
        }
    }


    @PostMapping("/login/forgetPwd")
    public ResponseEntity forgetPwd(@RequestBody UserLoginVo userLoginVo) {
        ResponseEntity responseEntity = loginByCaptcha(userLoginVo);

        User user = new User();
        user.setId((Integer) responseEntity.getData());
        user.setPassword(userLoginVo.getPassword());
        userService.updateByCondition(user);

        return responseEntity;
    }
}
